<?php

namespace app\api\controller;

use app\admin\model\Houses;
use app\common\model\imchat\Friends;
use app\common\model\UserCollect;
use Throwable;
use ba\Captcha;
use ba\ClickCaptcha;
use think\facade\Config;
use app\common\facade\Token;
use app\common\controller\Frontend;
use app\api\validate\User as UserValidate;

#[Apidoc\Title("用户中心")]
class User extends Frontend
{
    protected array $noNeedLogin = ['checkIn', 'logout'];

    protected array $noNeedPermission = ['*'];

    public function initialize(): void
    {
        parent::initialize();
    }

    /**
     * 会员签入(登录和注册)
     * @throws Throwable
     */
    #[
        Apidoc\Title("测试账号密码登录"),
        Apidoc\Tag("apidoc,基础,示例"),
        Apidoc\Method("POST"),
        Apidoc\Url("/api/user/checkIn"),
        Apidoc\Param(name: "tab", type: "string", require: true, desc: "login：登录，register：注册;", mock: "login"),
        Apidoc\Param(name: "username", type: "string", require: true, desc: "zhangsan", mock: "zhangsan"),
        Apidoc\Param(name: "password", type: "string", require: false, desc: "密码", mock: "admin123"),
        Apidoc\Param(name: "keep", type: "int", require: false, desc: "页码", mock: "1"),
        Apidoc\Returned("id", type: "int", desc: "Id"),
    ]
    public function checkIn(): void
    {
        $openMemberCenter = Config::get('buildadmin.open_member_center');
        if (!$openMemberCenter) {
            $this->error(__('Member center disabled'));
        }

        // 检查登录态
        if ($this->auth->isLogin()) {
            $this->success(__('You have already logged in. There is no need to log in again~'), [
                'type' => $this->auth::LOGGED_IN
            ], $this->auth::LOGIN_RESPONSE_CODE);
        }

        if ($this->request->isPost()) {
            $params = $this->request->post(['tab', 'email', 'mobile', 'username', 'password', 'keep', 'captcha', 'captchaId', 'captchaInfo', 'registerType']);
            if (!in_array($params['tab'], ['login', 'register'])) {
                $this->error(__('Unknown operation'));
            }

            $validate = new UserValidate();
            try {
                $validate->scene($params['tab'])->check($params);
            } catch (Throwable $e) {
                $this->error($e->getMessage());
            }

            if ($params['tab'] == 'login') {
//                $captchaObj = new ClickCaptcha();
//                if (!$captchaObj->check($params['captchaId'], $params['captchaInfo'])) {
//                    $this->error(__('Captcha error'));
//                }
                $res = $this->auth->login($params['username'], $params['password'], (bool)$params['keep']);
            } elseif ($params['tab'] == 'register') {
                $captchaObj = new Captcha();
                if (!$captchaObj->check($params['captcha'], ($params['registerType'] == 'email' ? $params['email'] : $params['mobile']) . 'user_register')) {
                    $this->error(__('Please enter the correct verification code'));
                }
                $res = $this->auth->register($params['username'], $params['password'], $params['mobile'], $params['email']);
            }

            if (isset($res) && $res === true) {
                $this->success(__('Login succeeded!'), [
                    'userInfo' => $this->auth->getUserInfo(),
                    'routePath' => '/user'
                ]);
            } else {
                $msg = $this->auth->getError();
                $msg = $msg ?: __('Check in failed, please try again or contact the website administrator~');
                $this->error($msg);
            }
        }

        $this->success('', [
            'accountVerificationType' => get_account_verification_type()
        ]);
    }

    #[
        Apidoc\Title("退出登录"),
        Apidoc\Tag("apidoc,基础,示例"),
        Apidoc\Method("GET"),
        Apidoc\Url("/api/user/logout"),
        Apidoc\Returned("id", type: "int", desc: "Id"),
    ]
    public function logout(): void
    {
        if ($this->request->isPost()) {
            $refreshToken = $this->request->post('refreshToken', '');
            if ($refreshToken) Token::delete((string)$refreshToken);
            $this->auth->logout();
            $this->success('退出登录成功');
        }
    }

    #[
        Apidoc\Title("客版房东详情、用户个人中心"),
        Apidoc\Tag("apidoc,基础,示例"),
        Apidoc\Method("POST"),
        Apidoc\Param(name: "uuid", type: "string", require: true, desc: "唯一id", mock: "20d7e351-7097-4daf-8d97-3586fbc72e40"),
        Apidoc\Param(name: "tab", type: "string", require: true, desc: "rent：租房，lookinng：找房;", mock: "rent"),
        Apidoc\Param(name: "page", type: "int", require: false, desc: "页码", mock: "1"),
        Apidoc\Param(name: "keyword", type: "string", require: false, desc: "关键词", mock: ""),
        Apidoc\Url("/api/user/usercenter"),
        Apidoc\Returned("user_info", type: "array", desc: "用户信息", mock: "has_attention 0未关注，1已关注"),
        Apidoc\Returned("user_info.id", type: "id", desc: "关注操作的to_uid", mock: "添加关注"),
    ]
    public function usercenter(): void
    {
        $uModel = new \app\common\model\User();
        $urow = $uModel->where('uuid', $this->request->post('uuid'))
            ->field('id,uuid,nickname,mobile,avatar,motto')
            ->cache()
            ->find();
        if (!$urow) {
            $this->error('用户不存在');
        }
        $tab_list = ['rent', 'looking','lookinng'];
        $tab = $this->request->post('tab');
        if (!in_array($tab, $tab_list)) {
            $this->error('参数错误');
        }
        $area = $this->request->param('city');
        $industry = $this->request->param('industry');
        $map = [];
        if (!empty($industry)) {
            $map[] = ['industry', 'in', $industry];
        }
        if ($area) {
            $map[] = ['city', 'like', '%' . $area . '%'];
        }
        $keyword = $this->request->param('keyword');
        if (!empty($keyword)) {
            $map[] = ['name', 'like', '%' . $keyword . '%'];
        }
        if ($tab == 'rent') {
            $tab_list = (new Houses())->where(['user_id' => $urow['id'],'status'=>1])->where($map)->paginate();
        } else {
            $tab_list = (new \app\common\model\Findstore())
                ->where(['user_id' => $urow['id'],'status'=>1])
                ->where($map)
                ->paginate();
        }
        $urow['has_attention'] = (new Friends())->where(['from_uid' => $this->auth->id, 'to_uid' => $urow['id']])->find() ? 1 : 0;
        $urow['rent_total']=(new Houses())->where(['user_id' => $urow['id'],'status'=>1])->where($map)->count();
        $urow['looking_total']=(new \app\common\model\Findstore())->where(['user_id' => $urow['id'],'status'=>1])->where($map)->count();
        $this->success('', [
            'user_info' => $urow,
            'tab_list' => $tab_list,
        ]);
    }

    #[
        Apidoc\Title("我的收藏"),
        Apidoc\Tag("apidoc,基础,示例"),
        Apidoc\Method("POST"),
        Apidoc\Param(name: "page", type: "int", require: false, desc: "页码", mock: "1"),
        Apidoc\Url("/api/user/mycollect"),
    ]
    public function mycollect()
    {
        $list = (new UserCollect())
            ->with('houses')
            ->where(['user_id' => $this->auth->id])
            //->where(['user_id' => 18])
            ->paginate();
        $this->success('我的收藏列表', $list);

    }

    #[
        Apidoc\Title("我的关注"),
        Apidoc\Tag("apidoc,基础,示例"),
        Apidoc\Method("POST"),
        Apidoc\Param(name: "page", type: "int", require: false, desc: "页码", mock: "1"),
        Apidoc\Url("/api/user/myattention"),
    ]
    public function myattention()
    {
        $list = (new Friends())
            ->field('id,create_time,to_uid')
            ->with('user')
            ->where([
                ['from_uid', '=', $this->auth->id],
                ['to_uid', '<>', 10]
            ])
            ->paginate()->each(function ($item) {
                $item->visible(['user.uuid', 'user.nickname', 'user.avatar']);
            });
        $this->success('我的关注', $list);
    }

    #[
        Apidoc\Title("添加关注"),
        Apidoc\Tag("apidoc,基础,示例"),
        Apidoc\Method("POST"),
        Apidoc\Param(name: "to_uid", type: "int", require: false, desc: "用户id", mock: "1"),
        Apidoc\Url("/api/user/addAttention"),
    ]
    public function addAttention()
    {
        if ((new Friends())
            ->where(['from_uid' => $this->auth->id, 'to_uid' => $this->request->post('to_uid')])->find()) {
            $this->error('已关注');
        } else {
            (new Friends())->create(['from_uid' => $this->auth->id, 'to_uid' => $this->request->post('to_uid')]);
            $this->success('关注成功');
        }
    }

    #[
        Apidoc\Title("取消关注"),
        Apidoc\Tag("apidoc,基础,示例"),
        Apidoc\Method("POST"),
        Apidoc\Param(name: "to_uid", type: "int", require: false, desc: "页码", mock: "1"),
        Apidoc\Url("/api/user/cancelAttention"),
    ]
    public function cancelAttention()
    {
        (new Friends())
            ->where(['from_uid' => $this->auth->id, 'to_uid' => $this->request->post('to_uid')])
            ->delete();
        $this->success('取消关注成功');
    }

    #[
        Apidoc\Title("查找用户"),
        Apidoc\Tag("apidoc,基础,示例"),
        Apidoc\Method("POST"),
        Apidoc\Param(name: "mobile", type: "string", require: true, desc: "手机号", mock: "14787826552"),
        Apidoc\Url("/api/user/searchUser"),
        Apidoc\Returned("id", type: "int", desc: "付款to_uid"),
        Apidoc\Returned("nickname", type: "sting", desc: "收款人名称"),
        Apidoc\Returned("gender_text", type: "sting", desc: "性别"),
        Apidoc\Returned("domain_avatar", type: "sting", desc: "头像"),
        Apidoc\Returned("mobile", type: "sting", desc: "手机号"),
    ]
    public function searchUser()
    {
        $mobile = $this->request->param('mobile');
        if (empty($mobile)) {
            $this->error('手机号不能为空');
        }
        $user = (new \app\common\model\User())
            ->where('mobile', $mobile)
            ->find();
        if (!$user) {
            $this->error('此手机号码尚未在本系统中注册，请核对');
        }
        $this->success('搜索结果', $user);
    }
}
